package com.indusfo.spc.controller;

import com.indusfo.spc.aspect.SystemControllerLog;
import com.indusfo.spc.interceptor.UserThreadLocal;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.UserService;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息控制器层
 *
 * @author xiet 2018年11月23日 下午2:41:25
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;

	@Resource
	private UploadMapper uploadMapper;

	/**
	 * 删除用户信息删除接口
	 * 
	 * @param lUserIdS
	 * @param lDataState
	 * @return
	 */
	@RequestMapping(value = "/deleteUser")
	@SystemControllerLog(description="删除用户信息")
//	@RequiresPermissions("user:shiro:delete")
	@ResponseBody
	public JSONObject deleteUser(Long[] lUserIdS, Integer lDataState) {
		lDataState = 2;
		JSONObject json = userService.deleteUser(lUserIdS, lDataState);
		// 没有异常，正常返回数据给前端
		return json;
	}

	/**
	 * 启停接口
	 * @Title: UserController
	 * @param lUserIdS
	 * @param lDataState
	 * @return
	 */
	@RequestMapping(value = "/definesUser")
	@SystemControllerLog(description="启停用户信息")
//	@RequiresPermissions("user:shiro:defines")
	@ResponseBody
	public JSONObject definesUser(Long[] lUserIdS, Integer lDataState) {

		JSONObject json = userService.deleteUser(lUserIdS, lDataState);
		// 没有异常，正常返回数据给前端
		return json;
	}
	
	/**
	 *	 新增用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/insertUser")
	@SystemControllerLog(description="新增用户信息")
	//@RequiresPermissions("user:shiro:add")
	@ResponseBody
	public JSONObject insertUser(User user) {
		JSONObject json = userService.insertUser(user);
		return json;
	}
	
	/**
	 * 	修改用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUser")
	@SystemControllerLog(description="修改用户信息")
	//@RequiresPermissions("user:shiro:update")
	@ResponseBody
	public JSONObject updateUser(User user) {
		JSONObject json  = userService.updateUser(user);
		return json;
	}
	
	/**
	 * 	查询用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping("/queryUser")
	@SystemControllerLog(description="查询用户信息")
	@ResponseBody
	public JSONObject queryUser(User user) {
		JSONObject jsonObject = userService.queryUser(user);
		return jsonObject;
	}

	/**
	 * 	查询用户信息   (用户表  部门表)
	 * @param user
	 * @return
	 */
	@RequestMapping("/queryUserDep")
	@SystemControllerLog(description="查询用户信息")
	@ResponseBody
	public JSONObject queryUserDep(User user) {
		JSONObject jsonObject = userService.queryUserDep(user);
		return jsonObject;
	}


	/**
	 * @Description: 获取当前线程用户
	 * @Params: []
	 * @Returns: com.indusfo.spc.vo.JSONObject
	 * @author: 余家能
	 * @date: 2019/2/25 3:09 PM
	 */
	@RequestMapping("/getThreadUser")
	@ResponseBody
	public JSONObject getThreadUserName(){
		JSONObject jsonObject = new JSONObject();
		try {
			User user = UserThreadLocal.get();
			jsonObject.victroy("获取当前用户成功！",user);
		}catch (Exception e){
			jsonObject.defeated("获取当前用户失败！");
			log.error("未知错误!",e);
		}
		return jsonObject;
	}

    /**
     * 通过角色ID查询该角色未设置的用户（角色）
     *
     * @param role
     * @return com.indusfo.spc.vo.JSONObject
     * @author xuz
     * @date 2019/7/17 3:41 PM
     */
    @RequestMapping("/queryUserByRoleId")
    @ResponseBody
    public JSONObject queryUserByRoleId(Role role) {
        List<User> userList = userService.queryUserByRoleId(role);
        return JSONObject.oK(userList, userService.getCountsByRoleId(role));
    }
	@RequestMapping("/uploadFileUser")
	@ResponseBody
    public JSONObject uploadFileUser(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
		//定义一个message对象用于向前台传输数据
		Message msg = new Message();
		//设置错误集合的
		List<ExcelErrorData> errorDatas = new ArrayList<>();
		response.setContentType("text/html;charset=UTF-8");
		//判断上传文件格式是否正确
		Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
		if (wb == null) {
			errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
		} else {
			//获取excel文件的第一个sheet
			Sheet sheet = wb.getSheetAt(0);
			if (sheet == null) {
				msg.setCode(2);
				msg.setMsg("未找到需要导入的表格");
				errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
			} else {
				//获取最后一行的行号
				int rowCount = sheet.getLastRowNum();
				if (rowCount < 1) {
					msg.setCode(1);
					msg.setMsg("未找到需要导入的数据，请确认表格是否保存！！！");
					errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
				} else {
					List<User> addProductPlans = new ArrayList<>();
					for (int i = 1; i <= rowCount; i++) {
						boolean needAdd = true;
						//获取到每一行的每一列的数据
						String vcUserCode =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
						String vcUserName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
						String lDepName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
						String vcUserPwd = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);
						User plan = new User(vcUserCode,vcUserName,lDepName,vcUserPwd);
						int m = i + 1;
						//将excel中的每一行数据存储进行检查
						String result = userService.checkNoRepeat(plan);
						if(result!=null){
							errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
							needAdd=false;
						}
						for (int j = 1; j < i; j++) {
							//判断用户编码是否重复
							String oldVcUserCode = StringUtils.trimToEmpty(com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false)).replaceAll("\\s*", "");
							if (StringUtils.isBlank(vcUserCode) &&  oldVcUserCode.equals(vcUserCode) ) {
								needAdd = false;
								errorDatas.add( ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同用户编码"));
							}
						}
						if (needAdd) {
							addProductPlans.add(plan);
						} else {
							msg.setCode(2);
							msg.setMsg("导入数据中存在异常信息");
						}

					}
					//根据这些来判断是否是中止导入还是跳过继续进行导入
					if (msg.getCode() == 2 && !way) {
						msg.setMsg(msg.getMsg() + ",中止导入");
					} else {
						if (addProductPlans.size() > 0) {
							try {
								userService.updateListUser(addProductPlans);
								//当程序执行到这里时,判断信息是否为空为空的话设置导入成功
								msg.setMsg(StringUtils.isBlank(msg.getMsg()) ? "导入成功" : msg.getMsg());
								if ("导入成功".equals(msg.getMsg())) {
									msg.setCode(1);
								}
							} catch (Exception e) {
								e.printStackTrace();
								msg.setMsg("导入失败");
							}
						}
					}
					//msg.setData(GsonUtil.toJson(errorDatas));
				}
			}
		}
		msg.setData(GsonUtil.toJson(errorDatas));
		//response.getWriter().println(GsonUtil.toJson(msg));
		String s = GsonUtil.toJson(msg);
		return JSONObject.build(200,msg.getMsg(),errorDatas);
	}



}
